#pragma once

#include "comm.hpp"

#define PATH "."
#define FILENAME "fifo"

using namespace std;

class NameFifo
{
public:
    NameFifo(const string &path, const string &name)
        :_path(path), _name(name)
    {
        _fifoname = _path + "/" + _name;
        umask(0);
        int n = mkfifo(_fifoname.c_str(), 0666);
        if(n != 0)
        {
            ERR_EXIT("mkfifo");
        }
        else 
        {
            cout << "mkfifo success" << endl;
        }
    }

    ~NameFifo()
    {
        int n = unlink(_fifoname.c_str());
        if(n == 0)
        {
            cout << "removefifo success" << endl;
        }
        else
        {
            //ERR_EXIT("unlink");
        }
    }
private:
    string _path;
    string _name;
    string _fifoname;
};

class FileOper
{
public:
    FileOper(const string &path, const string &name)
        :_path(path), _name(name)
    { _fifoname = _path + "/" + _name; }

    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open_file");
        }
        else 
        {
            cout << "open success" << endl;
        }
    }

    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if(_fd < 0)
        {
            cerr << "open error" << endl;
            exit(1);
        }
        else 
        {
            cout << "open success" << endl;
        }
    }

    bool Wait()
    {
        char c;
        int n = read(_fd, &c, 1);
        if(n > 0) return true;
        return false;
    }

    void WakeUp()
    {
        char c = 'a';
        write(_fd, &c, 1);
    }

    ~FileOper()
    {
        if(_fd > 0)
            close(_fd);
    }
private:
    string _path;
    string _name;
    string _fifoname;
    int _fd;
};